# 简单的并发测试脚本
import requests
import time
import threading
from concurrent.futures import ThreadPoolExecutor
import statistics


def test_server_connection():
    """测试服务器连接"""
    try:
        response = requests.get("http://127.0.0.1:8000/", timeout=5)
        print(f"✅ 服务器连接成功，状态码: {response.status_code}")
        return True
    except Exception as e:
        print(f"❌ 服务器连接失败: {e}")
        print("请确保Django服务器正在运行: python manage.py runserver")
        return False


def single_request(url, timeout=10):
    """单个请求测试"""
    start_time = time.time()
    try:
        response = requests.get(f"http://127.0.0.1:8000{url}", timeout=timeout)
        end_time = time.time()
        return {
            'status_code': response.status_code,
            'response_time': end_time - start_time,
            'success': response.status_code == 200,
            'url': url
        }
    except Exception as e:
        end_time = time.time()
        return {
            'status_code': 0,
            'response_time': end_time - start_time,
            'success': False,
            'error': str(e),
            'url': url
        }


def concurrent_test(url, concurrent_users=10, total_requests=100):
    """并发测试"""
    print(f"\n�� 开始测试: {url}")
    print(f"📊 并发用户: {concurrent_users}, 总请求数: {total_requests}")

    results = []
    start_time = time.time()

    with ThreadPoolExecutor(max_workers=concurrent_users) as executor:
        futures = [executor.submit(single_request, url) for _ in range(total_requests)]
        results = [future.result() for future in futures]

    end_time = time.time()
    total_time = end_time - start_time

    # 分析结果
    total = len(results)
    success = sum(1 for r in results if r['success'])
    failed = total - success
    response_times = [r['response_time'] for r in results if r['success']]

    print(f"\n�� 测试结果:")
    print(f"⏱️  总测试时间: {total_time:.3f}秒")
    print(f"�� 总请求数: {total}")
    print(f"✅ 成功请求: {success}")
    print(f"❌ 失败请求: {failed}")
    print(f"�� 成功率: {success / total * 100:.2f}%")
    print(f"🚀 QPS: {total / total_time:.2f}")

    if response_times:
        print(f"⏱️  响应时间:")
        print(f"   平均: {statistics.mean(response_times):.3f}秒")
        print(f"   最小: {min(response_times):.3f}秒")
        print(f"   最大: {max(response_times):.3f}秒")
        print(f"   中位数: {statistics.median(response_times):.3f}秒")

    # 性能评估
    print(f"\n🎯 性能评估:")
    if success / total >= 0.95:
        print("   ✅ 成功率优秀 (≥95%)")
    elif success / total >= 0.90:
        print("   ⚠️  成功率良好 (≥90%)")
    else:
        print("   ❌ 成功率需要改进 (<90%)")

    if response_times and statistics.mean(response_times) < 0.5:
        print("   ✅ 响应时间优秀 (<0.5秒)")
    elif response_times and statistics.mean(response_times) < 1.0:
        print("   ⚠️  响应时间良好 (<1.0秒)")
    else:
        print("   ❌ 响应时间需要改进 (≥1.0秒)")


def main():
    print("🧪 Django项目并发量测试")
    print("=" * 50)

    # 检查服务器连接
    if not test_server_connection():
        return

    # 测试用例
    test_cases = [
        ("/index/", 10, 200, "首页 - 低并发"),
        ("/index/", 15, 400, "首页 - 中等并发"),
        ("/login/", 10, 200, "登录页 - 低并发"),
        ("/project/list/", 30, 600, "项目列表 - 低并发"),
    ]

    for url, concurrent, total, desc in test_cases:
        print(f"\n{'=' * 60}")
        print(f"🔍 测试场景: {desc}")
        concurrent_test(url, concurrent, total)
        time.sleep(1)  # 测试间隔

    print(f"\n{'=' * 60}")
    print("🎉 测试完成！")
    print("\n💡 优化建议:")
    print("1. 如果响应时间过长，考虑优化数据库查询")
    print("2. 如果错误率较高，检查服务器资源")
    print("3. 可以尝试增加并发数找到性能瓶颈")


if __name__ == "__main__":
    main()